<template>
  <el-dialog
    :title="title"
    v-model="visible"
    align-center
    width="1000"
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <customsInfo
      ref="customsInfoRef"
      v-model="form"
      :info="info"
      :is_order_exist="is_order_exist"
    ></customsInfo>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button :loading="loading" type="primary" @click="save">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script setup name="customsDialog" lang="jsx">
import { ElMessage, ElMessageBox } from "element-plus";
import { reactive, toRefs } from "vue";
import customsInfo from "../customsInfo.vue";
import { isURL } from "@/utils/validate";
import { getMinPriceBySku, getUrlInfo, changeOrderExist } from "@/api/index.js";
import { change_order_category } from "@/utils/data.js";
import { deepClone } from "@/utils/index.js";
import { getCustomsDetail } from "@/api/index";

let handleType = reactive(inject("handleType"));

const visible = ref(false);
const loading = ref(false);
const emit = defineEmits(["close", "updateForm"]);
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {},
  },
  supplier: {
    type: Array,
    default: () => {
      return [];
    },
  },
  info: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const { info } = toRefs(props);

const statusMap = new Map([
  ["add", "新增报关信息"],
  ["edit", "编辑报关信息"],
]);

const data = reactive({
  title: "",
  form: {
    cn_name: "",
    en_name: "",
    cn_material: "",
    en_material: "",
    customs_code: "",
    declare_unit: "",
    purpose: "",
    declare_link: "",
    customs_quantity: 1,
  },
  is_order_exist: false,
});

const { title, form, is_order_exist } = toRefs(data);

// 打开弹窗
const open = async (type, row) => {
  title.value = statusMap.get(type);
  initForm();
  is_order_exist.value = await checkChangeOrderExist();

  visible.value = true;
  if (row) form.value = deepClone(row);
  if (form.value.goods_sku_customs_info.length == 0) {
    form.value.goods_sku_customs_info = [
      {
        customs_currency: "USD",
        country_id: null,
        country_name: "",
        customs_link: "",
        customs_price: "",
      },
    ];
  }
};

const initForm = () => {
  form.value = getForm();
};
// 初始化
const getForm = () => {
  return {
    cn_name: "",
    en_name: "",
    cn_material: "",
    en_material: "",
    customs_code: "",
    declare_unit: "",
    purpose: "",
    declare_link: "",
    customs_quantity: 1,
  };
};

const customsInfoRef = ref();
// 关闭弹窗
const close = () => {
  customsInfoRef.value.initComponent();
  visible.value = false;
};

// 提交
const countryMap = new Map([
  ["德国", "DE"],
  ["英国", "UK"],
  ["澳大利亚", "AU"],
  ["美国", "US"],
]);

const save = async () => {
  if (!customsInfoRef.value) return;
  const formData = Object.assign({}, form.value);
  if (formData.is_multi_platform && formData.goods_sku_customs_info.length < 2) {
    return ElMessage.error("当'是否多国家售卖'=是，则清关信息维护至少两条及以上");
  }

  const platformCountryPairs = formData.goods_sku_customs_info
    .filter((item) => !item.delete)
    .map((item) => [item.platform_name, item.country_id].join("-"));

  const hasUniquePairs =
    new Set(platformCountryPairs).size === platformCountryPairs.length;

  if (!hasUniquePairs) {
    ElMessage.error("平台和国家的组合不能相同；");
    return;
  }

  let massageDeclareArray = [];
  const skip_list = ["GTIN", "CAS", "其他"];
  formData.declare_elements_list.forEach((item, index) => {
    if (
      item.disabled &&
      item.text &&
      !skip_list.includes(item.text) &&
      (item.value === undefined || item.value === null || item.value === "")
    ) {
      massageDeclareArray.push(`申报要素维护项：第${index}项：值不能为空`);
    } else if (
      !item.disabled &&
      (!item.text || item.value === undefined || item.value === null || item.value === "")
    ) {
      massageDeclareArray.push(`申报要素维护项：第${index}项：维护项和值不能为空`);
    }
  });

  if (massageDeclareArray && massageDeclareArray.length) {
    return ElMessageBox({
      title: "提示",
      message: <div>{massageDeclareArray.map((d) => h("p", null, d))}</div>,
    });
  }

  let declare_elements = "";
  formData.declare_elements_list.forEach((item, index) => {
    const value = item.value;
    declare_elements += value;
    if (index < formData.declare_elements_list.length - 1) {
      declare_elements += "|";
    }
    item.sort = index;
    return item;
  });
  formData.declare_elements = declare_elements;

  if (info.value.is_refund_tax == 2 && Number(formData.tax_rebate_rate) == 0) {
    return ElMessage.error("退税供应商的退税率必须>0，请确认");
  }

  loading.value = true;

  if (info.value.is_refund_tax == 2) {
    const is_check = await ValidityDetection();
    if (is_check) {
      loading.value = false;
      return ElMessage.error(
        "您所选海关编码的特殊商品标识=1，不支持退税，无法保存，请更换海关编码"
      );
    }
  }
  loading.value = false;
  emit("updateForm", formData);
  close();
};

defineExpose({ open });

// 检测有没有待审核变更单
const checkChangeOrderExist = async () => {
  const is_change_order_category = change_order_category.includes(
    info.value.spu_category[0]
  );

  if (!info.value.sku_id || !is_change_order_category) {
    return false;
  }
  try {
    const res = await changeOrderExist({
      sku_id: info.value.sku_id,
      change_type: 2,
    });
    return res.data;
  } catch (e) {
    throw Error(e);
  }
};

// 海关编号合法判断
const ValidityDetection = () => {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await getCustomsDetail({
        customs_goods_code: form.value.customs_code,
      });
      if (res.data?.special_identify == 1) {
        resolve(true);
      } else {
        resolve(false);
      }
    } catch (e) {
      reject(false); // 使用 reject 传递错误
      throw Error(e);
    }
  });
};
</script>
